package com.java.example.ui.update

import android.Manifest
import android.annotation.TargetApi
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.java.example.R
import com.java.example.app.Constant
import com.java.example.app.Latte
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class UpdateService : Service() {
    private var apkUrl: String? = null
    private var notificationManager: NotificationManager? = null
    private var notification: Notification? = null

    override fun onCreate() {
        super.onCreate()
        notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
    }

    @TargetApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(channelId: String, channelName: String, importance: Int) {
        val channel = NotificationChannel(channelId, channelName, importance)
        channel.enableVibration(false)
        channel.setSound(null, null)
        val notificationManager = Latte.applicationContext.getSystemService( NOTIFICATION_SERVICE ) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }

    /**
     * 测试方法，发送通知
     */
    fun initNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "update"
            val channelName = "版本更新"
            val importance = NotificationManager.IMPORTANCE_HIGH
            createNotificationChannel(channelId, channelName, importance)
        }
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        if (intent == null) {
            notifyUser(getString(R.string.update_download_failed), getString(R.string.update_download_failed), 0)
            stopSelf()
            return super.onStartCommand(intent, flags, startId)
        }
        initNotification()
        apkUrl = intent.getStringExtra("apkUrl")
        notifyUser(getString(R.string.update_download_start), getString(R.string.update_download_start), 0)
        startDownload()
        return super.onStartCommand(intent, flags, startId)
    }

    private fun startDownload() {
        UpdateManager.instance.startDownloads("http://mencc.oss-cn-hangzhou.aliyuncs.com/measurement/2019-12/measurement.apk", Constant.APK_PATH, object : UpdateDownloadListener {
            override fun onStarted() {
//                Log.e("tag", "onStarted()");
            }

            override fun onProgressChanged(progress: Int, downloadUrl: String?) {
//                Log.e("onProgressChanged", progress+"");
                notifyUserNotCancel(getString(R.string.update_download_progressing), getString(R.string.update_download_progressing), progress)
            }

            override fun onFinished(completeSize: Float, downloadUrl: String?) {
//                Log.e("tag", "onFinished()");
                notifyUser(getString(R.string.update_download_finish), getString(R.string.update_download_finish), 100)
                stopSelf()
            }

            override fun onFailure() {
//                Log.e("tag", "onFailure()");
                notifyUser(getString(R.string.update_download_failed), getString(R.string.update_download_failed), 0)
                stopSelf()
            }
        })
    }

    /**
     * 更新notification
     * @param result
     * @param msg
     * @param progress
     */
    private fun notifyUser(result: String, msg: String, progress: Int) {
        val builder = NotificationCompat.Builder(this, "update")
        builder.setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
            .setContentText(" 下载进度：$progress%")
            .setContentTitle(getString(R.string.app_name))
            .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
            .setVibrate(longArrayOf(0))
            .setSound(null)
        if (progress in 1..100) {
            builder.setProgress(100, progress, false)
        } else {
            builder.setProgress(0, 0, false)
        }
        builder.setAutoCancel(true)
        builder.setWhen(System.currentTimeMillis())
        builder.setTicker(result)
        builder.setContentIntent(if (progress >= 100) contentIntent else PendingIntent.getActivity(this, 0, Intent(), if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_IMMUTABLE else PendingIntent.FLAG_UPDATE_CURRENT))
        notification = builder.build()
        notificationManager!!.notify(0, notification)
    }

    /**
     * 更新notification,点击不消失
     * @param result
     * @param msg
     * @param progress
     */
    private fun notifyUserNotCancel(result: String, msg: String, progress: Int) {
        val builder = NotificationCompat.Builder(this, "update")
        builder.setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
            .setContentText(" 下载进度：$progress%")
            .setContentTitle(getString(R.string.app_name))
            .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
            .setVibrate(longArrayOf(0))
            .setSound(null)
        if (progress in 1..100) {
            builder.setProgress(100, progress, false)
        } else {
            builder.setProgress(0, 0, false)
        }
        builder.setAutoCancel(false)
        builder.setWhen(System.currentTimeMillis())
        builder.setTicker(result)
        builder.setContentIntent(if (progress >= 100) contentIntent else PendingIntent.getActivity(this, 0, Intent(), if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_IMMUTABLE else PendingIntent.FLAG_UPDATE_CURRENT))
        notification = builder.build()
        notificationManager!!.notify(0, notification)
    }

    private val contentIntent: PendingIntent
        /**
         * 进入apk安装程序
         * @return
         */
        get() {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            val apkFile = File(Constant.APK_PATH)
            //        String ss=new String(FileUtils.getFileMD5ToString(apkFile));
//        Log.i("AAAA","ss md5:"+ss);
            var uri: Uri? = null
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(Latte.applicationContext, AppUtils.getAppPackageName() + ".provider", apkFile)
                intent.setDataAndType(uri, "application/vnd.android.package-archive")
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                //            Log.i("AAAA","uri:"+uri.getPath());
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    val hasInstallPermission = Latte.applicationContext.packageManager.canRequestPackageInstalls()
                    if (!hasInstallPermission) {
                        //请求安装未知应用来源的权限
                        PermissionUtils.permission(*arrayOf(Manifest.permission.REQUEST_INSTALL_PACKAGES)).callback(object : PermissionUtils.SimpleCallback {
                            override fun onGranted() {
                                CoroutineScope(Dispatchers.IO).launch {
                                    delay(1500)
                                    startActivity(intent)
                                }
                            }

                            override fun onDenied() {
                                ToastUtils.showLong("您已禁止安装app")
                            }
                        }).request()

                        //                    ActivityCompat.requestPermissions(Latte.getApplicationContext(), new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 6666);
                    }
                }
            } else {
                uri = Uri.fromFile(apkFile)
                intent.setDataAndType(uri, "application/vnd.android.package-archive")
            }
            //        intent.setDataAndType(uri,"application/vnd.android.package-archive");
            CoroutineScope(Dispatchers.IO).launch {
                delay(1500)
                startActivity(intent)
            }
            val pendingIntent = PendingIntent.getActivity(this, 0, intent, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_IMMUTABLE else PendingIntent.FLAG_UPDATE_CURRENT)
            return pendingIntent
        }

    /**
     * 进入apk安装程序
     * @return
     */
    /*private PendingIntent getContentIntent1() {
        String mimeDefault = "application/vnd.android.package-archive";
        String storagePath= Latte.getApplicationContext().getExternalFilesDir(null)+"/clds/measurement.apk";
        File apkFile = new File(storagePath);
        if (!apkFile.exists()) {
            return null;
        }
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            //兼容7.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //必须是addFlag setFlags 是覆盖权限
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                //这里牵涉到7.0系统中URI读取的变更
                Uri contentUri = FileProvider.getUriForFile(Latte.getApplicationContext(), AppUtils.getAppPackageName() + ".fileprovider", apkFile);
                intent.setDataAndType(contentUri, mimeDefault);
                //兼容8.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    boolean hasInstallPermission = Latte.getApplicationContext().getPackageManager().canRequestPackageInstalls();
                    if (!hasInstallPermission) {
                        startInstallPermissionSettingActivity();
                        return null;
                    }
                }
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), mimeDefault);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Latte.getApplicationContext().getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                //如果APK安装界面存在，携带请求码跳转。使用forResult是为了处理用户 取消 安装的事件。外面这层判断理论上来说可以不要，但是由于国内的定制，这个加上还是比较保险的
                startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
            } else {
                startActivity(intent);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }finally {
            //手动休眠5秒
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //特此记录不能加，不然加固包解析错误
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }*/
    override fun onBind(intent: Intent): IBinder? {
        return null
    }
}
